<template>
  <view class="vmall-classify">
    <view class="u-wrap">
      <search class="u-search-box" />
      <view class="u-menu-wrap">
        <scroll-view class="u-tab-view menu-scroll-view" :scroll-y="true" :scroll-with-animation="true"
          :scroll-top="scrollTop" :scroll-into-view="itemId">
          <view v-for="(item, index) in tabbar" :key="index" class="u-tab-item"
            :class="{ 'u-tab-item-active': current == index }" @click.stop="swichMenu(item,index)">
            <text class="u-line-1">{{ item.name }}</text>
            <text class="new" v-if="item.type=='2'&&item.showTag&&item.showTag==1">新</text>
          </view>
        </scroll-view>

        <scroll-view class="right-box" :scroll-top="scrollRightTop" :scroll-y="true" scroll-with-animation
          @scroll="rightScroll">
          <view class="page-view">
            <view v-for="(item, index) in tabbar" :key="index" :id="'item' + index" class="class-item"
              >
              <view class="item-title">
                <!--<view>{{ item.name }}</view>-->
                <view v-if="item.type=='0'" class="chevronright-content" @click.stop="toNextPage1(item)">
                  <view>查看全部</view>
                  <image class="chevronright" :src="IMG_URL2 + 'common/chevron-right.svg'"></image>
                </view>
              </view>
              <view class="item-container" v-if="item.type == '1'">
                <view v-for="(record, index1) in item.childrenList" :key="index1" class="thumb-box" @click="toNextPage(record)">
                  <image class="item-menu-image" :src="record.image" mode="" />
                  <view class="item-menu-name">{{ record.name }}</view>
                </view>
              </view>
              <!-- <view class="item-container" v-else-if="item.type == '2'">
                <view v-for="(record, index1) in item.childrenList" :key="index1" class="thumb-box" @click="toNextPage2(record)">
                  <image class="item-menu-image" :src="record.images" mode="" />
                  <view class="item-menu-name">{{ record.name }}</view>
                </view>
              </view> -->
              <view class="item-container1" v-else>
                <view v-for="(record, index1) in item.childrenList" :key="index1" class="thumb-box1" >
                  <ShopCard2 class="items" :item="record" />
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <SalesButton />
  </view>
</template>

<script setup>
import { getCurrentInstance } from "vue";
import { IMG_URL2 } from "@/config";
import search from "@/components/search/search.vue";
import ShopCard2 from "@/components/shop/card2.vue";
import { shopApi } from "@/api";
import SalesButton from "@/components/salesbutton.vue";

const instance = getCurrentInstance();
const scrollTop = ref(0); //tab标题的滚动条位置
const oldScrollTop = ref(0);
const current = ref(0); // 预设当前项的值
const menuHeight = ref(0); // 左边菜单的高度
const menuItemHeight = ref(0); // 左边菜单item的高度
const itemId = ref(""); // 栏目右边scroll-view用于滚动的id
const tabbar = ref([{
  name: '全部',
  type: '0',
  childrenList: []
}]);
const menuItemPos = ref([]);
const arr = ref([]);
const scrollRightTop = ref(0); // 右边栏目scroll-view的滚动条高度
const timer = ref(null); // 定时器

let pageSize = ref(10)
let currentPage = ref(1)
let totalCount = ref(0)
let isChildren = ref(false) //true 获得记录 false 使用记录
let loadStatus = ref('正在加载中')

onLoad(() => {
  fetchData()
});
// 点击左边的栏目切换
const swichMenu = async (item,index) => {
  console.log(item,index,'item,index')
  if (arr.value.length != tabbar.value.length) {
    await getMenuItemTop().then(() => {
      scrollRightTop.value = oldScrollTop.value;
      nextTick(() => {
        scrollRightTop.value = arr.value[index];
        current.value = index;
        leftMenuStatus(index);
      });
    })
  }
  if (item.type == '2') {
    tabbar.value.forEach(tab => {
      if (tab.type === '2') {
        tab.childrenList = []; // Set to empty array
      }
    });

    getSeriesdata(item.productSeriesId,index)
  }
  if (arr.value.length > 0) {
    if (index == current.value) return;
    scrollRightTop.value = oldScrollTop.value;
    nextTick(() => {
      scrollRightTop.value = arr.value[index];
      current.value = index;
      leftMenuStatus(index);
    });
  }
};
const getSeriesdata = (productSeriesId,index)=>{
  shopApi.CATEGORYGETFRONTPRODUCTLIST({
    currentPage: currentPage.value,
    pageSize: 4,
    productSeriesId:productSeriesId
  }).then(res => {
    if (res.code == 200) {
      if (  res.result.data.length > 0) {
        tabbar.value[index].childrenList = res.result.data
      }
    }
  })
}
// 获取一个目标元素的高度
const getElRect = (elClass, dataVal) => {
  new Promise((resolve, reject) => {
    const query = uni.createSelectorQuery().in(instance);
    query
      .select("." + elClass)
      .boundingClientRect((res) => {
        if (!res) {
          setTimeout(() => {
            getElRect(elClass);
          }, 10);
          return;
        }
        switch (dataVal) {
          case 1:
            menuHeight.value = res.height;
            break;
          case 2:
            menuItemHeight.value = res.height;
            break;
        }
      })
      .exec();
  });
};
// 观测元素相交状态
const observer = async () => {
  tabbar.value.map((val, index) => {
    let observer = uni.createIntersectionObserver(instance);
    // 检测右边scroll-view的id为itemxx的元素与right-box的相交状态
    // 如果跟.right-box底部相交，就动态设置左边栏目的活动状态
    observer
      .relativeTo(".right-box", {
        top: 0
      })
      .observe("#item" + index, (res) => {
        if (res.intersectionRatio > 0) {
          let id = res.id.substring(4);
          leftMenuStatus(id);
        }
      });
  });
};
// 设置左边菜单的滚动状态
const leftMenuStatus = async (index) => {
  current.value = index;
  // 如果为0，意味着尚未初始化
  if (menuHeight.value == 0 || menuItemHeight.value == 0) {
    await getElRect("menu-scroll-view", 1);
    await getElRect("u-tab-item", 2);
  }
  // 将菜单活动item垂直居中
  scrollTop.value = index * menuItemHeight.value + menuItemHeight.value / 2 - menuHeight.value / 2;
};
// 获取右边菜单每个item到顶部的距离
const getMenuItemTop = () => {
  arr.value = []
  return new Promise((resolve) => {
    let selectorQuery = uni.createSelectorQuery();
    selectorQuery
      .selectAll(".class-item")
      .boundingClientRect((rects) => {
        // 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
        // console.log(rects,'rects');
        if (!rects.length) {
          setTimeout(() => {
            getMenuItemTop();
          }, 10);
          return;
        }
        rects.forEach((rect) => {
          // 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
          arr.value.push(rect.top - rects[0].top);
          resolve();
        });
      })
      .exec();

  });

};
// 右边菜单滚动
const rightScroll = async (e) => {
  oldScrollTop.value = e.detail.scrollTop;
  if (arr.value.length != tabbar.value.length) {
    await getMenuItemTop().then(async () => {
      if (timer.value) return;
      if (!menuHeight.value) {
        await getElRect("menu-scroll-view", 1);
      }
      setTimeout(() => {
        // 节流
        timer.value = null;
        // scrollHeight为右边菜单垂直中点位置
        let scrollHeight = e.detail.scrollTop + menuHeight.value / 2;
        for (let i = 0; i < arr.value.length; i++) {
          let height1 = arr.value[i];
          let height2 = arr.value[i + 1];
          // 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
          if (!height2 || (scrollHeight >= height1 && scrollHeight < height2)) {
            leftMenuStatus(i);
            return;
          }
        }
      }, 10);
    });
  }
  if (arr.value.length > 0) {
    if (timer.value) return;
    if (!menuHeight.value) {
      await getElRect("menu-scroll-view", 1);
    }
    setTimeout(() => {
      // 节流
      timer.value = null;
      // scrollHeight为右边菜单垂直中点位置
      let scrollHeight = e.detail.scrollTop + menuHeight.value / 2;
      for (let i = 0; i < arr.value.length; i++) {
        let height1 = arr.value[i];
        let height2 = arr.value[i + 1];
        // 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
        if (!height2 || (scrollHeight >= height1 && scrollHeight < height2)) {
          leftMenuStatus(i);
          return;
        }
      }
    }, 10);
  }
};

async function fetchData() {
  try {
    const [response1, response2, response3] = await Promise.all([
      // 产品列表
      shopApi.CATEGORYGETFRONTPRODUCTLIST({
        currentPage: currentPage.value,
        pageSize: 4
      }),
      //获取分类列表一级分类
      shopApi.CATEGORYGETCATEGORYLIST({
        currentPage: currentPage.value,
        isChildren: true,
        pageSize: pageSize.value
      }),
      //获取系列
      shopApi.CATEGORYGETSERIESLIST({
        currentPage: currentPage.value,
        isChildren: false,
        pageSize: pageSize.value
      }),
      // axios.get('https://api.example.com/api3')
    ]);

    const data1 = response1;
    const data2 = response2;
    const data3 = response3;

    let newdata1 = [
      {
        name: '全部',
        type: '0',
        childrenList: data1.result.data.map(item => {
          return {
            ...item,
            imageurl: item.images ? item.images.split(',')[0] : '',
          }
        })
      }
    ]

    let newdata2 = data2.result.data.map(item => {
      return {
        ...item,
        type: '1',
        childrenList: item.childrenList ? item.childrenList : []
      }
    })
    let newdata3 = data3.result.data.map((item, index) => {
      return {
        ...item,
        type: '2',
        showTag: index < 3 ? 1 : 0, // Set showTag to 1 for the first three items, otherwise 0
        childrenList: item.childrenList ? item.childrenList : []
      }
    })
    tabbar.value = [...newdata1, ...newdata2, ...newdata3]
    getMenuItemTop();

  } catch (error) {
    console.error('请求出错:', error);
    // resultDiv.innerHTML = '请求接口出现错误，请稍后再试。';
  }
}



const toNextPage = (item) => {
  uni.navigateTo({
    url: '/pages/classify/subproduction?categoryId=' + item.categoryId + '&categoryName=' + item.name
  });
};

const toNextPage1 = (item) => {
  uni.navigateTo({
    url: '/pages/good/index'
  });
}
const toNextPage2 = (item) => {
  uni.navigateTo({
    url: `/pages/good/details?id=${item.productId}`
  });
}
</script>

<style lang="scss" scoped>
page {
  background-color: #ffffff;
}
</style>
<style lang="scss" scoped>
.vmall-classify {
  .u-wrap {
    height: calc(100vh);
    /* #ifdef H5 */
    height: calc(100vh - var(--window-bottom));
    /* #endif */
    display: flex;
    flex-direction: column;
  }

  .u-search-box {
    padding: 18rpx 30rpx;
    box-sizing: border-box;
    background-color: #ffffff;
  }

  .u-menu-wrap {
    // margin-top: 88rpx;
    /* #ifdef APP-PLUS */
    margin-top: calc(var(--status-bar-height) + 88rpx);
    /* #endif */
    flex: 1;
    display: flex;
    overflow: hidden;
  }

  .u-search-inner {
    // background-color: rgb(234, 234, 234);
    border-radius: 100rpx;
    display: flex;
    align-items: center;
    padding: 10rpx 16rpx;
    box-sizing: border-box;
  }

  .u-search-text {
    font-size: 26rpx;
    color: $u-tips-color;
    margin-left: 10rpx;
  }

  .u-tab-view {
    width: 200rpx;
    height: 100%;
  }

  .u-tab-item {
    height: 110rpx;
    background: #f6f6f6;

    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26rpx;
    color: #444;
    font-weight: 400;
    line-height: 1;
    padding-left: 10rpx;
    box-sizing: border-box;
    position: relative;
    .new{
      position: absolute;
      top: 0;
      right: 0;
      width: 30rpx;
      height: 30rpx;
      background: #ff0000;
      border-radius: 50%;
      color: #fff;
      font-size: 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .u-tab-item-active {
    position: relative;
    color: rgba(214, 142, 68, 1);
    font-size: 30rpx;
    font-weight: 600;
    background: #fff;
  }

  .u-tab-item-active::before {
    content: "";
    position: absolute;
    border-left: 4px solid rgba(214, 142, 68, 1);
    height: 32rpx;
    left: 0;
    top: 39rpx;
  }

  .right-box {
    background-color: rgb(250, 250, 250);
  }

  .page-view {
    padding: 16rpx;
    box-sizing: border-box;
  }

  .class-item {
    margin-bottom: 30rpx;
    background-color: #fff;
    padding: 16rpx;
    box-sizing: border-box;
    border-radius: 8rpx;
    height: 100vh;
  }

  .class-item:last-child {
    margin-bottom: 0rpx;
    // min-height: 100vh;
    min-height: calc(100vh - var(--window-bottom) - 288rpx);
  }

  .item-title {
    width: 100%;
    font-size: 26rpx;
    color: $u-main-color;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .chevronright-content {
			display: flex;
      align-items: center;

			.chevronright {
				width: 32rpx;
			  height: 32rpx;
        margin-left: 4rpx;
			}
		}
  }

  .item-menu-name {
    font-weight: normal;
    font-size: 24rpx;
    color: $u-main-color;
  }

  .item-container {
    display: flex;
    flex-wrap: wrap;

    .thumb-box {
      width: 33.333333%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      margin-top: 20rpx;
    }

    .item-menu-image {
      width: 96rpx;
      height: 96rpx;
    }
  }

  .item-container1 {
    display: flex;
    flex-wrap: wrap;
    padding: 12rpx 0 0 0;

    .thumb-box1 {
      width: 100%;
    }
  }


}
</style>
